<?php
/**
 * 功能描述：	ZHLCMS数据安装
 * @datetime	2023-02-24
 * @version   	v2.3.0
 * @author   	ZHL
 * @copyrigh  	2022 ZHL 版权所有
 */

class Admin_InstallController extends Controller {

    /**
     * Notes:登录_页面
     * User: ZhuHaili
     * Date: 2022/7/8
     */
    function index(){
        $manageKey = Fun::input('dev');
        $sysSer = new Admin_SystemServe();
        $dbFile = $sysSer->sysDBfile();
        $dbInfo = $manageKey == SYS_DEV_LOGIN_FLAG ? $sysSer->sysDBConfig() : array();
        $verifyFlag = isset($GLOBALS['ADMIN']['verify_flag']) ? $GLOBALS['ADMIN']['verify_flag'] : 0;
        $this->set('dbConf', $dbInfo);
        $this->set('dbFile', $dbFile);
        $this->set('title', 'ZHLCMS数据安装');
        $this->set('verifyFlag', $verifyFlag);
		$this->set('loginPic', SYS_LINK.$GLOBALS['ADMIN']['login_pic']);
        $this->set('manageKey', $manageKey);
		$this->display();
    }

    /**
     * @fun		数据库导入-开发者模式
     * @desc	sql文件导入到数据库
     */
    function setinfo(){
        $manageType = Fun::input('manage_type');
        $manageUser = Fun::input('manage_user');
        $managePwd = Fun::input('manage_pwd');
        $manageCode = Fun::input('manage_code');
        $manageKey = Fun::input('manage_key');
        $dbHost = Fun::input('db_host');
        $dbUser = Fun::input('db_user');
        $dbPass = Fun::input('db_pwd');
        $dbName = Fun::input('db_name');
        $filedb = Fun::input('filedb');

        // 用户信息检测
        $loginSer = new Admin_LoginServe();
        $userCheck = $loginSer->checkUser($manageUser, $managePwd, $manageCode, $manageKey);
        if($userCheck != 'Y'){
            htmlAlert($userCheck, SYS_URL_PATH('admin_install'));
        }

        $sysSer = new Admin_SystemServe;
        // 类型为1时修改配置
        if($manageType == 1){
            if(!$dbHost || !$dbUser || !$dbPass || !$dbName){
                htmlAlert('配置信息不能为空！', SYS_URL_PATH('admin_install'));
            }
            $dbInfo = $sysSer->sysDBConfig();
            $dbConfig['db_host'] = $dbHost;
            $dbConfig['db_name'] = $dbName;
            $dbConfig['db_user'] = $dbUser;
            $dbConfig['db_pwd'] = $dbPass;
            $dbConfig['db_fix'] = $dbInfo['db_fix'];
            $hint = $sysSer->updateDBConfig($dbConfig);
            if($hint == 'Y'){
                // 验证配置是否链接成功
                $conn = mysqli_connect($dbHost, $dbUser, $dbPass);
                if(!$conn){
                    htmlAlert('配置成功！检测链接失败', SYS_URL_PATH('admin_install'));
                }
                // 查库是否存在
                $sql = 'SELECT COUNT(*) AS `exists` FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMATA.SCHEMA_NAME="'.$dbName.'"';
                $query = mysqli_query($conn, $sql);
                if($query === false) {
                    htmlAlert('配置成功！判断库失败', SYS_URL_PATH('admin_install'));
                }
                $row = mysqli_fetch_array($query);
                if(!isset($row['exists'])){
                    htmlAlert('配置成功！判断库异常', SYS_URL_PATH('admin_install'));
                }
                // 不存在创建
                if($row['exists'] < 1){
                    $sql = 'CREATE DATABASE '.$dbName;
                    $retval = mysqli_query($conn, $sql);
                    if(!$retval){
                        htmlAlert('配置成功！建库失败', SYS_URL_PATH('admin_install'));
                    }
                    mysqli_close($conn);
                }
                htmlAlert('配置更新成功！', SYS_URL_PATH('admin_install'));
            }
            htmlAlert('配置更新失败！', SYS_URL_PATH('admin_install'));
        }
        // 数据导入
        if($manageType == 2){
            // 数据导入
            $dbPathFile = SYS_DB_PATH.$filedb;
            if(!file_exists($dbPathFile)){
                htmlAlert('数据文件不存！', SYS_URL_PATH('admin_install'));
            }
            $pathInfo = realpath($dbPathFile);

            $db = Model::conn('mysql');
            $dbConfig = $db->db_config;
            $config['type'] = $dbConfig['db_type'];
            $config['hostname'] = $dbConfig['db_host'];
            $config['hostport'] = $dbConfig['db_port'];
            $config['database'] = $dbConfig['db_name'];
            $config['username'] = $dbConfig['db_user'];
            $config['password'] = $dbConfig['db_pwd'];
            $config['charset'] = $dbConfig['db_char'];
            $config['path'] = str_replace($filedb,'', $pathInfo);
            register_shutdown_function(array($this, 'restoredb'), $config, $filedb);
            echo '正在导入,不要走开……';
            ob_flush();
            flush();exit;
        }
        // 初始化CMS
        if($manageType == 4){
            $paths = array();
            $paths[] = array('type'=>2, 'path'=>SYS_PATH.'app/web/controllers/Web_OtherController.php');
            $paths[] = array('type'=>2, 'path'=>SYS_PATH.'app/web/views/web_member/');
            $paths[] = array('type'=>1, 'path'=>SYS_PATH.'app/web/views/web_m/');
            $paths[] = array('type'=>1, 'path'=>SYS_PATH.'app/web/views/web_pc/');
            $paths[] = array('type'=>1, 'path'=>SYS_PATH.'public/uploads/');
            $paths[] = array('type'=>2, 'path'=>SYS_PATH.'public/html/');
            $paths[] = array('type'=>1, 'path'=>SYS_PATH.'public/web/');
            $paths[] = array('type'=>1, 'path'=>SYS_PATH.'runtime/');
            $paths[] = array('type'=>2, 'path'=>SYS_PATH.'README.md');
            foreach($paths as $p){
                if($p['type'] == 1){
                    delDir($p['path']);
                }else if($p['type'] == 2){
                    delDirFile($p['path']);
                }
                //rename("'".SYS_PATH.'README_CASE.md'."'", "'".SYS_PATH.'README.md'."'");
                //rename('README_CASE.txt', 'README.txt');

                SYS_ADD_FILE(SYS_PATH.'README.md', $this->readmeData());
                SYS_ADD_FILE(SYS_PATH.'app/web/views/web_m/index.html', $this->indexHtml());
                SYS_ADD_FILE(SYS_PATH.'app/web/views/web_pc/index.html', $this->indexHtml());
            }
            htmlAlert('初始化完成！', SYS_URL_PATH('admin_install'));
        }
        htmlAlert('Error:Type', SYS_URL_PATH('admin_install'));
    }

    /**
     * Notes: 异步导入
     * User: ZhuHaili
     * Date: 2022/12/2
     */
    public function restoredb($config, $filedb){
        $dbpdo = new ManageDbPDO($config);
        $r = $dbpdo->restore($filedb);
        if(!isset($r['code']) || $r['code'] != 200){
            htmlAlert('部分导入失败', SYS_URL_PATH('admin_install'));
        }
        htmlAlert('导入成功', SYS_URL_PATH('admin_install'));
    }

    /**
     * Notes:
     */
    private function readmeData(){
        return '
#### 项目说明    
> 项目名    
> 项目简介   
> 宣传式企业官网 / 商城类网站 / 新闻资讯……    

#### 运行条件   
> 脚本语言：PHP，版本5.3以上（建议php7）  
> 数据库：mysql，版本5.7  
> web服务器：Apache / Nginx / ISS    

#### 运行说明 
> 必须连接网络   
> 必须支持网页浏览的应用      
> 支持电脑、手机、平板等终端    

#### 技术    
> 原创界面设计，html5响应式源码编写，PC+M双模版，自开发PHP框架   
> Photoshop，VSCode，PhpStorm，Navicat等    

#### 协作者    
> 设计：xxx  
> 前端：xxx  
> 程序：Zhu  
';
    }

    /**
     * Notes:index初始内容
     */
    private function indexHtml(){
        return '
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>ZHLCMS</title>
    <meta name="keywords" content="">
    <meta name="description" content="">
    <!-- 设置缩放 -->
    <meta name="viewport" content="minimal-ui,width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <style>

    </style>
    <script>

    </script>
</head>
<body>
	<div>请开始你的创作……</div>
</body>
</html>
        ';
    }


}